package com.example.petplatform.service;

import com.example.petplatform.dao.DonationDao;
import com.example.petplatform.dao.DonationRecordDao;
import com.example.petplatform.dto.DonationAddDTO;
import com.example.petplatform.dto.DonationContributeDTO;
import com.example.petplatform.dto.DonationUpdateDTO;
import com.example.petplatform.entity.Donation;
import com.example.petplatform.entity.DonationRecord;
import com.example.petplatform.entity.Param.Params;
import com.example.petplatform.exception.CustomException;
import com.example.petplatform.vo.DonationStatisticsVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class DonationService {
   @Resource
    private DonationDao donationMapper;
    @Resource
    private DonationRecordDao donationRecordDao;
    /**
     * 分页查询捐赠项目列表
     */
    public PageInfo<Donation> donationSearch(Params params) {
        // 开启分页
        PageHelper.startPage(params.getPageNum(), params.getPageSize());
        // 执行查询
        List<Donation> list = donationMapper.donationSearch(params);
        // 返回分页信息
        return new PageInfo<>(list);
    }

    /**
     * 获取捐赠统计数据
     */
    public DonationStatisticsVO getStatistics() {
        return donationMapper.selectStatistics();
    }

    /**
     * 新增捐赠项目
     */
    public void add(DonationAddDTO addDTO) {
        Donation donation = new Donation();
        donation.setProject_name(addDTO.getProject_name());
        donation.setTarget_amount(addDTO.getTarget_amount());
        donation.setStart_date(addDTO.getStart_date());
        donation.setEnd_date(addDTO.getEnd_date());
        donation.setStatus("active");
        donation.setCurrent_amount(donation.getCurrent_amount() != null ? donation.getCurrent_amount() : new java.math.BigDecimal("0"));
        donation.setDonor_count(donation.getDonor_count() != null ? donation.getDonor_count() : 0);
        donation.setCreate_time(LocalDateTime.now());
        donation.setUpdate_time(LocalDateTime.now());
        donation.setIs_deleted(0);
        donation.setStart_date(donation.getStart_date() != null ? donation.getStart_date() : LocalDateTime.now());
        donation.setEnd_date(donation.getEnd_date() != null ? donation.getEnd_date() : LocalDateTime.now());
        //遍历donation
        System.out.println(donation.getProject_name());
        System.out.println(donation.getTarget_amount());
        System.out.println(donation.getStatus());
        System.out.println(donation.getStart_date());
        donationMapper.insert(donation);
    }

    /**
     * 更新捐赠项目
     */
    public void update(DonationUpdateDTO updateDTO) {
        Donation donation = donationMapper.selectById(updateDTO.getId());
        if (donation == null) {
            throw new CustomException("捐赠项目不存在");
        }

        BeanUtils.copyProperties(updateDTO, donation);
        System.out.println(donation.getProject_name());
        System.out.println(donation.getTarget_amount());
        donation.setUpdate_time(LocalDateTime.now());
        donationMapper.updateById(donation);
    }

    /**
     * 删除捐赠项目
     */
    public void delete(Long id) {
        Donation donation = donationMapper.selectById(id);
        if (donation == null) {
            throw new CustomException("捐赠项目不存在");
        }

        if ("completed".equals(donation.getStatus())) {
            throw new CustomException("已完成的项目不能删除");
        }

        // 逻辑删除
        donation.setIs_deleted(1);
        donation.setUpdate_time(LocalDateTime.now());
        donationMapper.updateById(donation);
    }

    /**
     * 处理捐款
     */
    @Transactional
    public void contribute(DonationContributeDTO contributeDTO) {
        // 1. 参数校验
        if (contributeDTO.getAmount() == null || contributeDTO.getAmount().compareTo(BigDecimal.ZERO) <= 0) {
            throw new CustomException("捐款金额必须大于0");
        }

        if (contributeDTO.getProjectId() == null) {
            throw new CustomException("项目ID不能为空");
        }

        // 2. 查询项目
        Donation donation = donationMapper.selectById(contributeDTO.getProjectId());
        if (donation == null) {
            throw new CustomException("捐赠项目不存在");
        }

        // 3. 检查项目状态
        if (!"active".equals(donation.getStatus())) {
            throw new CustomException("该项目已结束，无法捐款");
        }

        // 4. 检查捐款金额是否超过剩余所需金额
        BigDecimal remainingAmount = donation.getTarget_amount().subtract(donation.getCurrent_amount());
        if (contributeDTO.getAmount().compareTo(remainingAmount) > 0) {
            throw new CustomException("捐款金额不能超过剩余所需金额：" + remainingAmount);
        }

        // 5. 更新捐款金额和捐赠人数
        donation.setCurrent_amount(donation.getCurrent_amount().add(contributeDTO.getAmount()));
        donation.setDonor_count(donation.getDonor_count() + 1);
        donation.setUpdate_time(LocalDateTime.now());

        // 6. 检查是否达成目标
        if (donation.getCurrent_amount().compareTo(donation.getTarget_amount()) >= 0) {
            donation.setStatus("completed");
        }

        // 7. 更新数据库
        donationMapper.updateById(donation);

        // 8. 记录捐款记录
        saveDonationRecord(contributeDTO, donation);
    }

    /**
     * 保存捐款记录
     */
    private void saveDonationRecord(DonationContributeDTO contributeDTO, Donation donation) {
        DonationRecord record = new DonationRecord();
        record.setProjectId(donation.getId());
        record.setUserId(contributeDTO.getUserId());
        record.setAmount(contributeDTO.getAmount());
        record.setDonorName(contributeDTO.getDonorName());
        record.setMessage(contributeDTO.getMessage());
        record.setCreateTime(LocalDateTime.now());

        donationRecordDao.insert(record);
    }
}